package toy.keli.edic.ui.home.homescreen

import android.util.Log
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.tween
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.slideIn
import androidx.compose.animation.slideOut
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalInspectionMode
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import toy.keli.edic.R
import toy.keli.edic.data.GlobalVal
import toy.keli.edic.data.PreviewData
import toy.keli.edic.data.config.BookConf
import toy.keli.edic.data.config.PageConf
import toy.keli.edic.data.model.Article
import toy.keli.edic.data.plug.CategoryTree
import toy.keli.edic.ui.history.HistoryWords
import toy.keli.edic.ui.home.HomeEvents
import toy.keli.edic.ui.home.TAG
import toy.keli.edic.ui.home.WordModelViewModel
import toy.keli.edic.ui.main.extend.MainRun
import toy.keli.edic.ui.navigation.NavScreen
import toy.keli.edic.util.ActivityRun


@Composable
@Preview(showBackground = true)
fun DefaultPage(
                wordIndex: Int?=0,
                fromPage: Int=0,
                wordViewModel0: WordModelViewModel?=null,
) {
    var wordViewModel =
    if( LocalInspectionMode.current) {
        PreviewData.defaultPage();
    }else{
        wordViewModel0!!
    }

    val wordModelState by wordViewModel.wordState.collectAsState()
    val detailState by wordViewModel.detailState.collectAsState()
    val level by wordViewModel.selectLevel.collectAsState()
    val wordModel = wordModelState.wordModel
    if(!detailState && PageConf.getBoolean(PageConf.homePage.DefaultShowDetails,true)){
        wordViewModel.searchByText()
    }

    val selectLevel = level > -1 || BookConf.instance.name.isNotEmpty()
    val hasWord = wordModel?.word?.isNotEmpty() == true
    HistoryWords.add(wordModel)
    Box {
        Column {
            if (hasWord) {
                DefaultPageWordTitle(wordViewModel)
            }

            if (detailState) {
                if (hasWord) {
                    SearchComponent(wordModelState, wordViewModel) {
                        onOpenNextWord(wordIndex ?: 0, fromPage)
                        HistoryWords.reset()
                    }
                } else {
                    Column ( modifier = Modifier
                        .fillMaxSize(),
                        horizontalAlignment = Alignment.CenterHorizontally,
                        verticalArrangement = Arrangement.Center
                    ){
                        HistoryWordsShow()
                    }
                }
            } else {
                var pageOnClick = {}
                Column(
                    modifier = Modifier
                        .fillMaxSize()
                        .clickable { pageOnClick() },
                    horizontalAlignment = Alignment.CenterHorizontally,
                    verticalArrangement = Arrangement.Center
                ) {
                    if (hasWord) {
                        pageOnClick = { wordViewModel.searchByText() }
                        Text(
//                    text = "请回忆单词发音和释义",
                            text = stringResource(R.string.Recall),
                            style = MaterialTheme.typography.titleSmall,
                            color = MaterialTheme.colorScheme.onSurface,
                            modifier = Modifier.padding(5.dp)
                        )
                        Text(
//                    text = "点击屏幕显示答案",
                            text = stringResource(R.string.Click),
                            style = MaterialTheme.typography.titleSmall,
                            color = MaterialTheme.colorScheme.onSurface
                        )
                    } else if (HomeEvents.onBeforeSelectBook()) {  //选择词库之前做单词列表设置 比如： 历史还是词典
                        pageOnClick = { NavScreen.BookmarkScreen.open() }
                        Text(
//                    text = "请点击选择词库",
                            text = stringResource(R.string.Selectdatabase),
                            style = MaterialTheme.typography.titleMedium,
                            color = MaterialTheme.colorScheme.onSurface,
                        )
                    }
                }
            }
        }

        AnimatedVisibility(
            visible = HomeEvents.downMenuOpen,
            enter = slideIn ( animationSpec = tween(durationMillis = 500),
                initialOffset = { fullSize ->
                    // fullSize 是组件的尺寸（宽x高）
                    IntOffset(x = 0, y = -fullSize.height) // X不变，Y轴负方向（上）偏移
                }),
            exit = slideOut(animationSpec = tween(durationMillis = 500),
                targetOffset = { fullSize ->
                    IntOffset(x = 0, y = -fullSize.height) // X不变，Y轴正方向（下）偏移
                })
        ) {
            GroupTools()
        }
    }
}

inline fun onOpenNextWord(wordIndex:Int=0,fromPage:Int=0){
    val uOrder = PageConf.getBoolean(PageConf.homePage.NextUnordered)
    GlobalVal.wordViewModel.showNext(uOrder)
}
